
import 'package:media_kit/ffi/ffi.dart';

import '../pojo/srtspan.dart';

class SrtTools
{
  static List<SrtSpan> handleSrtContent(String content) {
    var result = <SrtSpan>[];
    var lines = <String>[];
    content = content.replaceAll("\r\n", "\n");
    lines = content.split("\n");
    print("总行数:${lines.length}");

    for (int i = 0; i < lines.length; i++) {
      String line1 = lines[i];
      if (line1.length < 1) {
        print("空行跳过");
        continue;
      }

      if (isNumeric(line1)) {
        // 时间间隔
        i++;
        String line2 = lines[i];
        if (line2.indexOf("-->") != -1) {
          var times = line2.split("-->");
          if (times.length == 2) {
            String startTime = times[0].trim();
            String endTime = times[1].trim();

            i++;
            String line3 = lines[i];
            print("编号:" + line1);
            print("开始时间:" + startTime);
            print("结束时间:" + endTime);
            print("字幕内容:" + line3);

            String nextLine = "";
            do {
              i++;
              if(i>=lines.length) break;
              nextLine = lines[i];
              if (nextLine.length > 0) {
                line3 += "\n" + nextLine;
              }
            } while (nextLine.length > 0);

            SrtSpan srt = new SrtSpan();
            srt.id = int.parse(line1);
            srt.startTime = toMicroSecond(startTime);
            srt.endTime = toMicroSecond(endTime);
            srt.content = line3;
            result.add(srt);
          } else {
            print("没有-->");
          }
        } else {
          print("数字后面不是时间间隔,不处理");
        }
      }
    }
    return result;
  }

  static bool isNumeric(String str) {
    return int.tryParse(str) != null;
  }

  static int toMicroSecond(String str) {
    // 00:21:15,707
    var tmp1 = str.split(",");
    var tmp2 = tmp1[0]; // 00:21:15
    var tmp3 = tmp1[1]; // 707
    var tmp4 = tmp2.split(":"); // 00 21 15
    var result = ((int.parse(tmp4[0]) * 60 + int.parse(tmp4[1])) * 60 +
        int.parse(tmp4[2])) *
        1000 +
        int.parse(tmp3);
    return result;
  }
}